<template>
	<view class="rain-container">
		<view v-for="n in 20" :key="n" class="rain-drop" :style="{ 
			left: Math.random() * 100 + 'vw',
			animationDuration: (Math.random() * 1 + 0.5) + 's',
			animationDelay: (Math.random() * 2) + 's'
		}"></view>
	</view>

	<view class="container">
		<!-- 顶部版本信息卡片 -->
		<view class="version-card">
			<image src="/static/delault/version.png" mode="aspectFit" class="version-icon"></image>
			<view class="version-info">
				<text class="version-title">版本信息</text>
				<view class="version-row">
					<text class="label">当前版本</text>
					<text class="value">{{ localVersion }}</text>
				</view>
				<view class="version-row">
					<text class="label">最新版本</text>
					<text class="value">{{ currentVersion?.version || '1.0.0' }}</text>
				</view>
				
				<!-- 版本状态提示 -->
				<view class="version-status" :class="{ 'need-update': !isLatestVersion }">
					<text class="iconfont" :class="isLatestVersion ? 'icon-qp_icon_check success' : 'icon-about warning'"></text>
					<text>{{ isDevelopment ? '开发版本' : (isLatestVersion ? '已是最新版本' : '发现新版本') }}</text>
				</view>
				
				<!-- 更新按钮 -->
				<button v-if="!isLatestVersion" 
						class="update-btn" 
						@click="startDownload(currentVersion.download_url)"
						:disabled="isDownloading">
					<text class="iconfont icon-cloud_computing_"></text>
					{{ isDownloading ? '正在更新...' : '立即更新' }}
				</button>
			</view>
		</view>

		<!-- 更新日志列表 -->
		<view class="update-logs">
			<view class="section-title animate__animated animate__fadeInDown">
				<text class="iconfont icon-icon-xinxi"></text>
				更新日志
			</view>
			
			<!-- 开发版本提示 -->
			<view v-if="isDevelopment" class="dev-tip">
				<image src="/static/delault/dev.png" mode="aspectFit" class="dev-icon"></image>
				<view class="dev-text">
					<text class="title">开发阶段</text>
					<text class="desc">当前处于开发阶段,暂无版本记录</text>
				</view>
			</view>
			
			<view class="log-list" v-else>
				<view v-for="(version, index) in versionList" 
					  :key="version.id" 
					  class="log-item animate__animated"
					  :class="{ 
						'current': version.version === currentVersion?.version,
						'animate__fadeInUp': true
					  }"
					  :style="{ animationDelay: index * 0.1 + 's' }">
					<view class="log-header" @click="toggleContent(version.id)">
						<view class="left">
							<text class="version-tag">v{{ version.version }}</text>
							<text class="time">{{ version.create_time }}</text>
						</view>
						<text class="iconfont" :class="isContentVisible(version.id) ? 'icon-icon-up' : 'icon-icon_down_arrow'"></text>
					</view>
					
					<view class="log-content" 
						  :id="'content-' + version.id"
						  v-show="isContentVisible(version.id)"
						  :class="{ 
							'content-visible': isContentVisible(version.id),
							'content-hidden': !isContentVisible(version.id)
						  }">
						<view v-for="(content, index) in version.contents" 
							  :key="index"
							  class="content-item"
							  :class="getContentClass(content.type)">
							<text class="type-tag">{{ content.type }}</text>
							<text class="desc">{{ content.text }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 下载进度弹窗 -->
		<view class="download-modal" v-if="isDownloading">
			<view class="modal-content">
				<view class="progress-info">
					<image src="/static/delault/downloading.gif" mode="aspectFit" class="download-icon"></image>
					<text class="title">正在下载更新</text>
					<text class="subtitle">请勿关闭应用</text>
					<text class="progress-text">{{ downloadProgress }}%</text>
				</view>
				
				<view class="progress-wrapper">
					<!-- 进度条背景 -->
					<view class="progress-bar">
						<!-- 进度条前景 -->
						<view class="progress-inner" :style="{ width: downloadProgress + '%' }">
							<!-- 进度条光效 -->
							<view class="progress-light"></view>
						</view>
					</view>
					<!-- 进度条下方的进度描述 -->
					<view class="progress-desc">
						<text>下载中...</text>
						<text>{{ formatSize(downloadedSize) }}/{{ formatSize(totalSize) }}</text>
					</view>
				</view>
				
				<button class="cancel-btn" 
						@click="closeDownloadModal"
						:disabled="downloadProgress === 100">
					{{ downloadProgress === 100 ? '正在安装...' : '取消更新' }}
				</button>
			</view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
// 基础样式
.container {
	min-height: 100vh;
	background: #f5f7fa;
	padding: 30rpx;
	position: relative;
	z-index: 2;
	
	.version-card {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 30rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
		backdrop-filter: blur(10px);
		animation: cardFloat 3s ease-in-out infinite;
		
		.version-icon {
			width: 120rpx;
			height: 120rpx;
			margin-right: 30rpx;
			animation: iconRotate 20s linear infinite;
		}
		
		.version-info {
			flex: 1;
			
			.version-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
			}
			
			.version-row {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;
				
				.label {
					font-size: 28rpx;
					color: #666;
					width: 140rpx;
				}
				
				.value {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
			}
			
			.version-status {
				display: flex;
				align-items: center;
				margin-top: 20rpx;
				padding: 10rpx 20rpx;
				border-radius: 30rpx;
				background: #f0f9eb;
				width: fit-content;
				
				.iconfont {
					margin-right: 10rpx;
					font-size: 32rpx;
					
					&.success {
						color: #67c23a;
					}
					
					&.warning {
						color: #e6a23c;
					}
				}
				
				text {
					font-size: 26rpx;
					color: #67c23a;
				}
				
				&.need-update {
					background: #fdf6ec;
					
					text {
						color: #e6a23c;
					}
				}
			}
			
			.update-btn {
				margin-top: 30rpx;
				background: linear-gradient(135deg, #007AFF, #0056b3);
				color: #fff;
				border-radius: 40rpx;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				overflow: hidden;
				
				&::before {
					content: '';
					position: absolute;
					top: -50%;
					left: -50%;
					width: 200%;
					height: 200%;
					background: radial-gradient(circle, rgba(255,255,255,0.3) 0%, transparent 60%);
					transform: rotate(45deg);
					animation: buttonGlow 3s linear infinite;
				}
				
				.iconfont {
					margin-right: 10rpx;
					font-size: 36rpx;
				}
				
				&:active {
					transform: scale(0.95);
				}
				
				&:disabled {
					opacity: 0.7;
				}
			}
		}
	}
	
	.update-logs {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
		backdrop-filter: blur(10px);
		
		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 30rpx;
			display: flex;
			align-items: center;
			
			.iconfont {
				font-size: 36rpx;
				margin-right: 10rpx;
				color: #007AFF;
			}
		}
		
		.log-list {
			.log-item {
				margin-bottom: 20rpx;
				border-radius: 12rpx;
				background: #f8f9fa;
				overflow: hidden;
				transition: all 0.3s ease;
				
				&:hover {
					transform: translateX(10rpx);
				}
				
				&.current {
					border: 2rpx solid #007AFF;
					background: #f0f7ff;
				}
				
				.log-header {
					padding: 20rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					cursor: pointer;
					position: relative;
					overflow: hidden;
					
					&::after {
						content: '';
						position: absolute;
						top: 0;
						left: -100%;
						width: 100%;
						height: 100%;
						background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
						animation: shine 2s infinite;
					}
					
					.left {
						display: flex;
						align-items: center;
						
						.version-tag {
							font-size: 28rpx;
							font-weight: bold;
							color: #333;
							margin-right: 20rpx;
						}
						
						.time {
							font-size: 24rpx;
							color: #999;
						}
					}
					
					.iconfont {
						font-size: 32rpx;
						color: #999;
						transition: transform 0.3s ease;
					}
				}
				
				.log-content {
					padding: 20rpx;
					border-top: 1rpx solid #eee;
					transition: all 0.3s ease-in-out;
					overflow: hidden;
					
					&.content-visible {
						max-height: 1000rpx;
						opacity: 1;
						transform: translateY(0);
					}
					
					&.content-hidden {
						max-height: 0;
						opacity: 0;
						transform: translateY(-10rpx);
						padding-top: 0;
						padding-bottom: 0;
					}
					
					.content-item {
						display: flex;
						align-items: flex-start;
						margin-bottom: 16rpx;
						animation: slideIn 0.3s ease-out;
						animation-fill-mode: both;
						
						@for $i from 1 through 10 {
							&:nth-child(#{$i}) {
								animation-delay: $i * 0.1s;
							}
						}
						
						.type-tag {
							padding: 4rpx 12rpx;
							border-radius: 4rpx;
							font-size: 24rpx;
							margin-right: 10rpx;
							min-width: 80rpx;
							text-align: center;
						}
						
						.desc {
							flex: 1;
							font-size: 26rpx;
							color: #666;
							line-height: 1.6;
						}
						
						&.content-new .type-tag {
							background: #f0f9eb;
							color: #67c23a;
						}
						
						&.content-optimize .type-tag {
							background: #f4f4f5;
							color: #909399;
						}
						
						&.content-fix .type-tag {
							background: #fef0f0;
							color: #f56c6c;
						}
						
						&.content-delete .type-tag {
							background: #fdf6ec;
							color: #e6a23c;
						}
						
						&.content-visible {
							opacity: 1;
							transform: translateX(0);
						}
						
						&.content-hidden {
							opacity: 0;
							transform: translateX(-20rpx);
						}
					}
				}
			}
		}
	}
}

// 下载弹窗样式
.download-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0,0,0,0.6);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 999;
	
	.modal-content {
		width: 600rpx;
		background: rgba(255, 255, 255, 0.95);
		border-radius: 20rpx;
		padding: 40rpx;
		backdrop-filter: blur(10px);
		
		.progress-info {
			text-align: center;
			margin-bottom: 30rpx;
			
			.download-icon {
				width: 120rpx;
				height: 120rpx;
				margin-bottom: 20rpx;
			}
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.subtitle {
				font-size: 26rpx;
				color: #999;
			}
			
			.progress-text {
				font-size: 40rpx;
				font-weight: bold;
				color: #007AFF;
				margin-top: 20rpx;
			}
		}
		
		.progress-wrapper {
			margin: 40rpx 0;
			
			.progress-bar {
				height: 16rpx;
				background: #f5f5f5;
				border-radius: 8rpx;
				overflow: hidden;
				position: relative;
				
				.progress-inner {
					height: 100%;
					background: linear-gradient(90deg, #007AFF, #00c6ff);
					border-radius: 8rpx;
					transition: width 0.3s linear;
					position: relative;
					
					.progress-light {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						background: linear-gradient(
							90deg,
							transparent,
							rgba(255, 255, 255, 0.5),
							transparent
						);
						animation: progressLight 2s ease-in-out infinite;
					}
				}
			}
			
			.progress-desc {
				display: flex;
				justify-content: space-between;
				margin-top: 10rpx;
				font-size: 24rpx;
				color: #666;
			}
		}
		
		.cancel-btn {
			margin-top: 30rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 30rpx;
			color: #666;
			background: #f5f5f5;
			transition: all 0.3s ease;
			
			&:active {
				transform: scale(0.98);
				opacity: 0.9;
			}
			
			&:disabled {
				opacity: 0.5;
				background: #e0e0e0;
				cursor: not-allowed;
			}
		}
	}
}

// 保留之前的动画关键帧定义
@keyframes rainDrop {
	0% {
		transform: translateY(-100vh);
		opacity: 0;
	}
	50% {
		opacity: 1;
	}
	100% {
		transform: translateY(100vh);
		opacity: 0;
	}
}

@keyframes ripple {
	0% {
		transform: scale(0);
		opacity: 1;
	}
	100% {
		transform: scale(1);
		opacity: 0;
	}
}

@keyframes cardFloat {
	0%, 100% {
		transform: translateY(0);
	}
	50% {
		transform: translateY(-10rpx);
	}
}

@keyframes iconRotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

@keyframes shine {
	0% {
		left: -100%;
	}
	100% {
		left: 100%;
	}
}

@keyframes slideIn {
	from {
		opacity: 0;
		transform: translateX(-30rpx);
	}
	to {
		opacity: 1;
		transform: translateX(0);
	}
}

@keyframes buttonGlow {
	0% {
		transform: rotate(45deg) translateY(-100%);
	}
	100% {
		transform: rotate(45deg) translateY(100%);
	}
}

@keyframes progressLight {
	0% {
		transform: translateX(-100%);
	}
	100% {
		transform: translateX(100%);
	}
}

// 添加箭头图标的旋转动画
.log-header {
	.iconfont {
		transition: transform 0.3s ease-in-out;
		
		&.icon-icon-up {
			transform: rotate(180deg);
		}
		
		&.icon-icon_down_arrow {
			transform: rotate(0deg);
		}
	}
}

// 添加开发版本提示样式
.dev-tip {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.9);
	padding: 30rpx;
	border-radius: 16rpx;
	margin: 20rpx 0;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	
	.dev-icon {
		width: 120rpx;
		height: 120rpx;
		margin-right: 20rpx;
	}
	
	.dev-text {
		flex: 1;
		
		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 8rpx;
			display: block;
		}
		
		.desc {
			font-size: 28rpx;
			color: #666;
			line-height: 1.4;
		}
	}
}
</style>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { api } from '@/utils/request'

const versionList = ref([])
const currentVersion = ref(null)
const localVersion = ref('1.0.0') // 设置默认版本号
const visibleContentIds = ref([]) // 存储可见内容的版本 ID
const isLatestVersion = ref(false) // 是否是最新版本
const isDownloading = ref(false) // 是否正在下载
const downloadProgress = ref(0) // 下载进度
const downloadedSize = ref(0)
const totalSize = ref(0)

const animatingIds = ref(new Set())

// 添加下载任务的引用
const currentDownloadTask = ref(null)

// 新增开发状态标识
const isDevelopment = ref(false)

const fetchVersionList = async () => {
	try {
		const response = await api.request({
			url: '/api/system/version/',
			method: 'GET'
		})
		if (response.code === 200) {
			// 判断是否有版本列表数据
			if(!response.data || response.data.length === 0) {
				isDevelopment.value = true
				versionList.value = []
			} else {
				isDevelopment.value = false
				versionList.value = response.data
			}
		} else {
			uni.showToast({
				title: response.msg || '获取版本列表失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取版本列表失败', error)
		uni.showToast({
			title: '获取版本列表失败',
			icon: 'none'
		})
		isDevelopment.value = true
	}
}

const fetchCurrentVersion = async () => {
	try {
		const response = await api.request({
			url: '/api/system/version/current/',
			method: 'GET'
		})
		if (response.code === 200) {
			// 判断是否有版本数据
			if(!response.data || Object.keys(response.data).length === 0) {
				isDevelopment.value = true
				currentVersion.value = {
					version: '1.0.0',
					download_url: '',
					descriptions: []
				}
			} else {
				isDevelopment.value = false
				currentVersion.value = response.data
			}
			compareVersions(currentVersion.value.version) // 比较版本
		} else {
			uni.showToast({
				title: response.msg || '获取当前版本失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取当前版本失败', error)
		uni.showToast({
			title: '获取当前版本失败',
			icon: 'none'
		})
		isDevelopment.value = true
	}
}

const compareVersions = (serverVersion) => {
	if (localVersion === serverVersion) {
		isLatestVersion.value = true
	} else {
		isLatestVersion.value = false
		uni.showToast({
			title: '有新版本可用，请更新！',
			icon: 'none'
		})
	}
}

const formatSize = (bytes) => {
	if (!bytes || bytes === 0) return '0 B'
	const k = 1024
	const sizes = ['B', 'KB', 'MB', 'GB']
	const i = Math.floor(Math.log(bytes) / Math.log(k))
	return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

const startDownload = async (url) => {
	try {
		isDownloading.value = true
		downloadProgress.value = 0
		downloadedSize.value = 0
		totalSize.value = 0

		// 等待视图更新
		await nextTick()

		// 先获取文件大小
		const sizeRes = await uni.request({
			url: url,
			method: 'HEAD'
		})

		const contentLength = sizeRes.header['Content-Length'] || sizeRes.header['content-length']
		if (contentLength) {
			totalSize.value = parseInt(contentLength)
		}

		// 创建下载任务
		currentDownloadTask.value = uni.downloadFile({
			url: url,
			success: async (res) => {
				if (res.statusCode === 200) {
					try {
						const saveRes = await uni.saveFile({
							tempFilePath: res.tempFilePath
						})
						
						await uni.openDocument({
							filePath: saveRes.savedFilePath
						})
						
						uni.showToast({
							title: '下载并安装成功',
							icon: 'success'
						})
					} catch (err) {
						console.error('文件处理失败:', err)
						uni.showToast({
							title: '文件处理失败',
							icon: 'none'
						})
					}
				} else {
					throw new Error('下载失败')
				}
			},
			fail: (err) => {
				if (err.errMsg && err.errMsg.includes('abort')) {
					uni.showToast({
						title: '已取消更新',
						icon: 'none'
					})
				} else {
					console.error('下载失败:', err)
					uni.showToast({
						title: '下载失败',
						icon: 'none'
					})
				}
			},
			complete: () => {
				// 使用 nextTick 确保状态更新
				nextTick(() => {
					isDownloading.value = false
					currentDownloadTask.value = null
				})
			}
		})

		// 监听下载进度
		currentDownloadTask.value.onProgressUpdate((res) => {
			nextTick(() => {
				if (res.totalBytesExpectedToWrite > 0) {
					totalSize.value = res.totalBytesExpectedToWrite
				}
				downloadedSize.value = res.totalBytesWritten
				downloadProgress.value = Math.floor((res.totalBytesWritten / totalSize.value) * 100)
			})
		})

	} catch (error) {
		console.error('更新失败:', error)
		uni.showToast({
			title: '更新失败',
			icon: 'none'
		})
		closeDownloadModal()
	}
}

const closeDownloadModal = async () => {
	try {
		if (currentDownloadTask.value) {
			currentDownloadTask.value.abort()
			currentDownloadTask.value = null
		}
		
		await nextTick()
		isDownloading.value = false
		downloadProgress.value = 0
		downloadedSize.value = 0
		totalSize.value = 0
	} catch (error) {
		console.error('关闭弹窗失败:', error)
	}
}

const getContentClass = (type) => {
	switch (type) {
		case "新增": return 'content-new'    // 新增
		case "优化": return 'content-optimize' // 优化
		case "修复": return 'content-fix'      // 修复
		case "删除": return 'content-delete'    // 删除
		default: return ''
	}
}

const toggleContent = (id) => {
	if (animatingIds.value.has(id)) return // 如果正在动画中，忽略点击
	
	animatingIds.value.add(id)
	
	if (visibleContentIds.value.includes(id)) {
		visibleContentIds.value = visibleContentIds.value.filter(item => item !== id)
	} else {
		visibleContentIds.value.push(id)
	}
	
	// 动画结束后移除动画状态
	setTimeout(() => {
		animatingIds.value.delete(id)
	}, 300) // 与 CSS transition 时间相同
}

const isContentVisible = (id) => {
	return visibleContentIds.value.includes(id)
}

onMounted(async () => {
	try {
		await Promise.all([
			fetchVersionList(),
			fetchCurrentVersion()
		])
	} catch (error) {
		console.error('初始化失败:', error)
	}
})
</script> 